package com.jie.generator.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jie.common.utils.ServletUtils;
import com.jie.common.utils.StringUtils;
import com.jie.generator.constant.GenConstants;
import com.jie.generator.entity.GenTable;
import com.jie.generator.entity.GenTableColumn;
import com.jie.generator.mapper.GenTableColumnMapper;
import com.jie.generator.mapper.GenTableMapper;
import com.jie.generator.service.GenTableService;
import com.jie.generator.utils.GenUtils;
import com.jie.generator.utils.VelocityInitializer;
import com.jie.generator.utils.VelocityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @description:
 * @author: xiaojie
 * @since: 2024/12/12 0012
 */
@Slf4j
@Service
public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements GenTableService {

    @Autowired
    private GenTableColumnMapper genTableColumnMapper;

    /**
     * 查询数据库列表
     * @param genTable 业务信息
     * @return 数据库表集合
     */
    @Override
    public IPage<GenTable> selectDbTableList(GenTable genTable) {
        Page mpPage =new Page(Convert.toLong(ServletUtils.getParameterToInt("pageNum"),1L)
                ,Convert.toLong(ServletUtils.getParameterToInt("pageSize"),10L));
        return baseMapper.selectDbTableList(mpPage,genTable);
    }

    /**
     * 查询据库列表
     * @param tableNames 表名称组
     * @return 数据库表集合
     */
    @Override
    public List<GenTable> selectDbTableListByNames(String[] tableNames) {
        return baseMapper.selectDbTableListByNames(tableNames);
    }

    /**
     * 导入表结构
     * @param tableList 导入表列表
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importGenTable(List<GenTable> tableList) {
        if (CollectionUtil.isNotEmpty(tableList)) {
            for (GenTable table : tableList) {
                String tableName = table.getTableName();
                GenUtils.initTable(table);
                // 保存生成表数据
                int row = baseMapper.insert(table);
                if (row > 0) {
                    // 查询数据库表列信息
                    List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
                    if (CollectionUtil.isNotEmpty(genTableColumns)) {
                        for (GenTableColumn column : genTableColumns) {
                            GenUtils.initColumnField(column, table);
                            // 保存生成表字段数据
                            genTableColumnMapper.insert(column);
                        }
                    }
                }
            }
        }
    }

    /**
     * 查询业务列表
     * @param genTable 业务信息
     * @return 业务集合
     */
    @Override
    public List<GenTable> selectGenTableList(GenTable genTable) {
        return baseMapper.selectGenTableList(genTable);
    }

    /**
     * 预览代码
     * @param tableId 表编号
     * @return 预览数据列表
     */
    @Override
    public Map<String, String> previewCode(Long tableId) {
        Map<String, String> dataMap = new LinkedHashMap<>();
        // 查询表信息
        GenTable table = baseMapper.selectGenTableById(tableId);
        // 查询子表信息
        List<GenTableColumn> genTableColumn = genTableColumnMapper.selectList(
                new LambdaQueryWrapper<GenTableColumn>().eq(GenTableColumn::getTableId,tableId));
       //new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getUserId())
        if (StringUtils.isNotEmpty(genTableColumn)) {
            table.setColumns(genTableColumn);

        }
        System.out.println("table测试："+table);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        //  初始化
        VelocityInitializer.initVelocity();
        // 设置模板变量信息
        VelocityContext context = VelocityUtils.prepareContext(table);
        // 获取模版列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template,"UTF-8");
            tpl.merge(context, sw);
            dataMap.put(template,sw.toString());
        }
        return dataMap;
    }

    /**
     * 生成代码（下载方式）
     * @param tableName 表名称
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String tableName) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 批量生成代码（下载方式）
     * @param tableNames 表数组
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName: tableNames) {
            generatorCode(tableName, zip);
        }
        IoUtil.close(zip);
        return outputStream.toByteArray();
    }

    /**
     * 删除业务信息
     * @param tableIds 需要删除的表数据ID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteGenTableByIds(Long[] tableIds) {
        baseMapper.deleteBatchIds(Arrays.asList(tableIds));
        List<GenTableColumn> genTableColumns = genTableColumnMapper.selectList(new LambdaQueryWrapper<GenTableColumn>().in(GenTableColumn::getTableId,Arrays.asList(tableIds)));
        genTableColumnMapper.deleteBatchIds(genTableColumns);
    }

    /**
     * 查询业务信息
     * @param id 业务ID
     * @return 业务信息
     */
    @Override
    public GenTable selectGenTableById(Long id) {
        GenTable genTable = baseMapper.selectGenTableById(id);
        setTableFromOptions(genTable);
        return genTable;
    }

    /**
     * 查询所有表信息
     * @return 表信息集合
     */
    @Override
    public List<GenTable> selectGenTableAll() {
        return baseMapper.selectGenTableAll();
    }

    /**
     * 修改保存参数校验
     * @param genTable 业务信息
     */
    @Override
    public void validateEdit(GenTable genTable) {
        String options = JSON.toJSONString(genTable.getParams());
        genTable.setOptions(options);
        int row = baseMapper.updateById(genTable);
        if (row > 0) {
            for (GenTableColumn cenTableColumn : genTable.getColumns()) {
                genTableColumnMapper.updateGenTableColumn(cenTableColumn);
            }
        }
    }

    /**
     * 修改业务
     *
     * @param genTable 业务信息
     * @return 结果
     */
    @Override
    public void updateGenTable(GenTable genTable) {
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
            String options = JSON.toJSONString(genTable.getParams());
            JSONObject paramsObj = JSON.parseObject(options);
            if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) {
                throw new RuntimeException("树编码字段不能为空");
            } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) {
                throw new RuntimeException("树父编码字段不能为空");
            } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) {
                throw new RuntimeException("树名称字段不能为空");
            } else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory())) {
                if (StringUtils.isEmpty(genTable.getSubTableName())) {
                    throw new RuntimeException("关联子表的表名不能为空");
                } else if (StringUtils.isEmpty(genTable.getSubTableFkName())) {
                    throw new RuntimeException("子表关联的外键名不能为空");
                }
            }
        }
    }

    private void generatorCode(String tableName, ZipOutputStream zip) {
        // 查询表信息
        GenTable table = baseMapper.selectGenTableByName(tableName);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        //  初始化
        VelocityInitializer.initVelocity();
        // 设置模板变量信息
        VelocityContext context = VelocityUtils.prepareContext(table);
        // 获取模版列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template,"UTF-8");
            tpl.merge(context, sw);
            try {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template,table)));
                IoUtil.write( zip, false, sw.toString().getBytes());
                IoUtil.close(sw);
                zip.flush();
                zip.closeEntry();
            } catch (IOException e) {
                log.error("渲染模板失败，表名：" + table.getTableName(), e);
            }
        }
    }

    /**
     * 设置主子表信息
     * @param table
     */
    public void setSubTable(GenTable table) {
        String subTableName = table.getSubTableName();
        if (StringUtils.isNotBlank(subTableName)) {

        }
    }

    /**
     * 设置主键列信息
     * @param table 业务表信息
     */
    public void setPkColumn(GenTable table) {
        for (GenTableColumn column : table.getColumns()) {
            if ("1".equals(column.getIsPk())) {
                table.setPkColumn(column);
                break;
            }
            if (StringUtils.isNull(table.getPkColumn())) {
                table.setPkColumn(table.getColumns().get(0));
            }
            if (GenConstants.TPL_SUB.equals(table.getTplCategory())) {
                for (GenTableColumn columnSub : table.getSubTable().getColumns()) {
                    if ("1".equals(columnSub.getIsPk())) {
                        table.getSubTable().setPkColumn(columnSub);
                        break;
                    }
                    if (StringUtils.isNull(table.getSubTable().getPkColumn())) {
                        table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
                    }
                }
            }
        }
    }

    /**
     * 设置代码生成其他选项值
     *
     * @param genTable 设置后的生成对象
     */
    public void setTableFromOptions(GenTable genTable) {
        JSONObject paramsObj = JSON.parseObject(genTable.getOptions());
        if (StringUtils.isNotNull(paramsObj)) {
            String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
            String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
            String treeName = paramsObj.getString(GenConstants.TREE_NAME);
            Long parentMenuId = paramsObj.getLongValue(GenConstants.PARENT_MENU_ID);
            String parentMenuName = paramsObj.getString(GenConstants.PARENT_MENU_NAME);

            genTable.setTreeCode(treeCode);
            genTable.setTreeParentCode(treeParentCode);
            genTable.setTreeName(treeName);
            genTable.setParentMenuId(String.valueOf(parentMenuId));
            genTable.setParentMenuName(parentMenuName);
        }
    }

}
